from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
import logging
import os
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

from .services import command_parser
from k8s_ops.services import k8s_service
from .models import VoiceProcessingJob
from .baidu_speech import speech_recognizer
from utils.common_utils import get_request_user
from utils.voice_command_processor import voice_command_processor 

logger = logging.getLogger(__name__)

@api_view(['POST'])
@permission_classes([])
def upload_voice_file(request):
    """上传语音文件并识别"""
    logger.debug("收到语音文件上传请求")
    
    if 'audio_file' not in request.FILES:
        logger.warning("请求中未找到audio_file字段")
        return Response({"error": "请提供语音文件"}, status=status.HTTP_400_BAD_REQUEST)
    
    audio_file = request.FILES['audio_file']
    supported_formats = ['.wav', '.mp3', '.m4a', '.amr', '.aac', '.pcm']
    file_ext = os.path.splitext(audio_file.name.lower())[1]
    
    logger.debug(f"上传文件: {audio_file.name}, 大小: {audio_file.size} bytes, 类型: {file_ext}")
    
    if file_ext not in supported_formats:
        logger.warning(f"不支持的格式: {file_ext}")
        return Response({"error": f"不支持的文件格式: {file_ext}"}, status=status.HTTP_400_BAD_REQUEST)
    
    # 获取用户
    user = get_request_user(request)
    if not user:
        logger.error("用户认证失败")
        return Response({"error": "用户认证失败"}, status=status.HTTP_401_UNAUTHORIZED)
    
    logger.debug(f"使用用户: {user.username}")
    
    try:
        # 保存文件
        file_path = default_storage.save(f'audio_uploads/{audio_file.name}', ContentFile(audio_file.read()))
        full_path = default_storage.path(file_path)
        logger.debug(f"文件保存成功: {full_path}")
        
        # 创建处理记录
        job = VoiceProcessingJob.objects.create(
            user=user,
            audio_file=file_path,
            status='uploaded'
        )
        logger.debug(f"创建语音处理任务: ID={job.id}")
        
        # 语音识别
        logger.debug("开始语音识别...")
        success, result = speech_recognizer.recognize_audio_file(full_path, file_ext.lstrip('.'))
        
        if success:
            logger.debug(f"语音识别成功，文本内容: '{result}'")
            job.original_text = result
            job.status = 'transcribed'
            job.save()
            
            # 继续处理指令
            logger.debug("开始处理识别后的指令...")
            return voice_command_processor.process_voice_command_internal(result, job)
        else:
            logger.error(f"语音识别失败: {result}")
            job.status = 'failed'
            job.validation_message = result
            job.save()
            return Response({"error": result}, status=status.HTTP_400_BAD_REQUEST)
            
    except Exception as e:
        logger.error(f"处理语音文件失败: {e}", exc_info=True)
        return Response({"error": f"处理失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([])
def process_voice_command(request):
    """处理文本指令（原有的文本接口）"""
    text = request.data.get('text', '').strip()
    
    if not text:
        return Response({"error": "缺少文本内容"}, status=status.HTTP_400_BAD_REQUEST)
    
    # 获取用户（使用全局工具函数）
    user = get_request_user(request)
    if not user:
        return Response({"error": "用户认证失败"}, status=status.HTTP_401_UNAUTHORIZED)
    
    # 创建处理记录
    job = VoiceProcessingJob.objects.create(
        user=user,
        original_text=text,
        status='uploaded'
    )
    
    
    return voice_command_processor.process_voice_command_internal(text, job)
   
